﻿package com.vinyl.events
{
	import flash.errors.IllegalOperationError;
	import flash.events.IOErrorEvent;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.events.EventDispatcher;
	import flash.net.URLVariables;
	import flash.system.System;
	import flash.xml.XMLDocument;
	
	public class DataService extends EventDispatcher
	{
		private static var instance:DataService;

		public function DataService() 
		{
			if(instance != null)
			{
				throw new Error("DataService Singleton already constructed!");
			}
		}
		
		public static function getInstance():DataService
		{
			if(instance == null)
			{
				instance=new DataService();
			}
			
			return instance;
		}
		
		private function nocache():String
		{
			return ("nocache=" + Math.random().toString());
		}
		
		public function getXML( xmlUrl:String ):void
		{
			trace("usecodepage : " + System.useCodePage);
			
			var loader:URLLoader=new URLLoader();			
			loader.dataFormat=URLLoaderDataFormat.TEXT;
			loader.addEventListener( Event.COMPLETE, getXML_onComplete );
			loader.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
			
			var queryString:String;
			queryString = xmlUrl;// + "?" + nocache();
				
			trace("queryString : " + queryString);
			
			try {
				loader.load(new URLRequest( queryString ) );
			} catch ( error:Error ) {
				trace( "Unable to load requested document." );
				dispatchEvent( new DataEvent( error, "error" ) );
			}
			
		}
		
		private function getXML_onComplete( e:Event ):void
		{
			var data=new XML( e.target.data );
			dispatchEvent(new DataEvent( data, DataEvent.GETDATA ) );
		}
		
		private function ioErrorHandler( event:IOErrorEvent ):void
		{
           dispatchEvent( new DataEvent( event, "error" ) );
        }
	}
}
